﻿using System.Data;
using System.Data.Common;
using System.Data.SqlClient;

namespace Common.Utility
{
    public static class ParamConvert
    {
        /// <summary>
        /// ParamCollection 转换具有基本属性的 DbParameter[]
        /// </summary>
        /// <param name="queryParam"></param>
        /// <returns></returns>
        public static DbParameter[] ToArrDbParameter(ParamCollection queryParam)
        {
            DbParameter[] parameters = new SqlParameter[queryParam.Length];

            if (queryParam != null)
            {
                int i = 0;
                foreach (Param param in queryParam.ToParamList())
                {
                    parameters[i] = ToDbParameter(param);
                    i += 1;
                }
            }
            return parameters;
        }

        /// <summary>
        /// ParamCollection 转换全部定义属性的 DbParameter[]
        /// </summary>
        /// <param name="queryParam"></param>
        /// <returns></returns>
        public static DbParameter[] ToArrCompDbParameter(ParamCollection queryParam)
        {
            DbParameter[] parameters = new SqlParameter[queryParam.Length];

            if (queryParam != null)
            {
                int i = 0;
                foreach (Param param in queryParam.ToParamList())
                {
                    parameters[i] = ToCompDbParameter(param);
                    i += 1;
                }
            }
            return parameters;
        }

        /// <summary>
        /// Param 转换为 DbParameter
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public static DbParameter ToDbParameter(Param param)
        {
            return new SqlParameter(param.KeyParam, param.ValueParam);
        }
        /// <summary>
        /// Param 转换为 DbParameter
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public static DbParameter ToCompDbParameter(Param param)
        {
            DbParameter dbParameter = new SqlParameter(param.KeyParam, (SqlDbType)param.ParamType, param.Size);

            if (!(param.InOutType == ParameterDirection.Output && param.ValueParam == null))
                dbParameter.Value = param.ValueParam;

            if (param.InOutType != 0)
                dbParameter.Direction = param.InOutType;

            return dbParameter;
        }

    }
}
